#!/usr/bin/python
# -*- coding: utf-8 -*-
# coding=utf-8
'''
Created on 2015年10月5日
v1.0 打包工具
@author: scott.lee
'''

import commands
import sys
import getopt
import os

PROJECT_PATH = '/home/administrator/Project/java/ycecs_v1.1/ycecs-web/target/ycecs_cn/'

'''
' 解压缩补丁包
'''


def explodeTarFile(patch_file):  # 读取tar包文件
    print "==============================解压缩补丁包=============================="
    (status, output) = commands.getstatusoutput('ls')
    if patch_file in output:
        mkdir_name = patch_file[:-7]
        print("创建文件夹 %s" % mkdir_name)
        commands.getstatusoutput("mkdir %s" % mkdir_name)
        print ("开始解压缩文件")
        cmd = "tar -zxvf %s" % patch_file + " -C ./%s" % patch_file[:-7]
        (status, output) = commands.getstatusoutput(cmd)
        # print output
        return mkdir_name
    else:
        print "不存在此补丁"


'''
' 创建回滚文件
'''


def create_roll_back_file(explodeTarFilePath):
    print "==============================开始创建回滚文件=============================="
    commands.getstatusoutput("mkdir %s" % explodeTarFilePath + "/rollback")
    path = explodeTarFilePath
    fns = [os.path.join(root, fn) for root, dirs, files in os.walk(path) for fn in files]
    for f in fns:
        tmp = f.split("/")
        roll_back_path = explodeTarFilePath + "/rollback/" + '/'.join(tmp[2:-1])
        cmd = "mkdir -p %s" % roll_back_path  # 创建补丁文件的文件夹路径
        commands.getstatusoutput(cmd)
        cmd = "cp  %s" % PROJECT_PATH + '/'.join(tmp[2:len(tmp)]) + " %s" % roll_back_path
        commands.getstatusoutput(cmd)
        print("备份文件%s" % PROJECT_PATH + '/'.join(tmp[2:len(tmp)]) + "\n>>>>>>>> %s" % roll_back_path)


'''
升级补丁主方法
'''


def patch_update(patch_file):
    explodeTarFilePath = explodeTarFile(patch_file)  # 解压缩补丁文件

    create_roll_back_file(explodeTarFilePath)  # 创建回滚文件

    execute_patch(explodeTarFilePath)
    print ("升级:" + patch_file + "补丁文件")


'''
拷贝补丁文件下的内容到目标目录下
'''


def execute_patch(explodeTarFilePath):
    print('==============================开始升级==============================')
    fns = [os.path.join(root, fn) for root, dirs, files in os.walk(explodeTarFilePath) for fn in files]
    for f in fns:
        tmp = f.split("/")
        if tmp[1] == 'patch':
            update_path = "%s" % PROJECT_PATH + '/'.join(tmp[2:len(tmp) - 1])
            update_file = "%s" % PROJECT_PATH + '/'.join(tmp[2:len(tmp)])
            print '目标文件夹[%s' % update_path + ']'
            if os.path.exists(update_path) == False: #判断文件夹是否存在，如果原来没有此次文件夹，则需要创建一个文件夹
                commands.getstatusoutput('mkdir -p %s' % update_path)
                # 创建回滚删除记录
                delete_record = open('%s'%explodeTarFilePath+'/rollback/delete_record.log', 'a')
                delete_record.write(update_path + '\n')
                delete_record.close()
            if os.path.exists(update_file) == False: #判断文件是否存在，如果没有此次文件,则需要删除增加回滚删除记录，增加删除记录前，判断是否次文件夹是否有删除记录如果有，则不需要增加文件删除记录

                try:
                    delete_record = open('%s'%explodeTarFilePath+'/rollback/delete_record.log','r')
                    delete_record.seek(0)
                    textlist = delete_record.readlines()
                    flag=False
                    for line in textlist:
                        if update_file.startswith(line)==True:
                            flag=True
                    delete_record.close()
                except Exception:
                    flag=True

                if flag:
                    delete_record = open('%s'%explodeTarFilePath+'/rollback/delete_record.log','a')
                    delete_record.write(update_file + '\n')
                    delete_record.close()
            print(update_path)
            cmd = 'cp ' + '/'.join(tmp) + " %s" % update_path
            commands.getstatusoutput(cmd)
            print("升级文件%s" % cmd)
    print("执行升级脚本")


'''
'判断输入的文件是否有效
'有效返回0，无效返回1
'''


def check_patch_is_valid(input):
    if input.endswith('.tar.gz'):
        return 0
    else:
        return 1


def patch_roll_back(value):
    comfim = raw_input('rollback %s' % value + ' please confirm(y)')
    print(comfim, (comfim is 'y'))
    if (comfim is 'y'):
        print('==============================开始回滚 %s==============================' % value)
        fns = [os.path.join(root, fn) for root, dirs, files in os.walk(value) for fn in files]
        for f in fns:
            tmp = f.split("/")
            if tmp[1] == 'rollback':
                taget_path = "%s" % PROJECT_PATH + '/'.join(tmp[2:len(tmp) - 1])
                cmd = 'cp ' + '/'.join(tmp) + " %s" % taget_path
                commands.getstatusoutput(cmd)
                print("回滚文件%s" % cmd)
            if tmp[2]=='delete_record.log':
                delete_record = open('%s'%value+'/rollback/delete_record.log','r')
                delete_record.seek(0)
                textlist = delete_record.readlines()
                for line in textlist:
                    cmd = 'rm -rf %s'%line[:-1]
                    commands.getstatusoutput(cmd)

    else:
        print "exit!"


def helpTip():
    print "patch.py [option] [补丁文件名]\n -h 获取帮助 -u 升级 -r 回滚 补丁文件必须已tar.gz为后缀"


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hu:r:")
        if len(opts) == 0:
            helpTip()
        for op, value in opts:
            if op == "-u":
                if check_patch_is_valid(value) == 1:  # 判断输入是否有效，为1无效，跳出
                    sys.exit()
                else:
                    patch_update(value)
            elif op == "-r":
                patch_roll_back(value)
            elif op == "-h":
                helpTip()
                sys.exit()
    except Exception, ex:
        print ex
        sys.exit()
#if __name__ == '__main__':
#   patch_update('patch_20151005.tar.gz')
